using System;
using System.Collections.Generic;
using System.Text;

using XGAE.Framework;

using xBody = XGAE.Framework.Body;
using xBackend = XGAE.Framework.Backend;

namespace XGAE.Body.Physics
{
    /// <summary>
    /// Wrapper class that implements all of the glue-code to get the module working.  
    /// </summary>
    class PhysicsManager : PhysicsModule
    {
        #region C'tors

        public PhysicsManager()
            : base()
        { }

        #endregion

        /// <summary>
        /// Return a new interface of a given type.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override Interface Export(string name)
        {
            if (name == "State")
            {
                Interface i = new PhysicsState(this) as Interface;
                this._stateChannel.Add(i);
                return i;
            }
            if (name == "Relative")
            {
                Interface i = new PhysicsRelative(this) as Interface;
                return i;
            }
            if (name == "Conversion")
            {
                Interface i = new PhysicsConversion(this) as Interface;
                return i;
            }

            //Warning("Component " + m_type + " does not export interface '" + name + "'.", __FILE__, __LINE__);
            return null;
        }

        /// <summary>
        /// Store dependencies for convenience, as passed by the architecture.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        public override bool Import(string name, Interface i)
        {
            if (name == "backend"  &&  Interface.IsCompatible(i.Version, 0x0003))
            {
                _backend = i as xBackend.IPhysics;
                i.RegisterListener( this );
                if (_backend != null)
                    return true;
            }

            //Warning( "Component " + m_type + " cannot import interface '" + name + "'.", __FILE__, __LINE__ );
            return false;
        }

        /// <summary>
        /// Internal hard-coded table to dispatch the messages automatically.
        /// </summary>
        /// <param name="m"></param>
        public override void Dispatch(Message message)
        {
            if (message >= "Collision")
            {
                xBody.Physics.CollisionMessage m = (xBody.Physics.CollisionMessage)message;
                OnCollision(m.Normal);
            }
            if (message >= "Update")
            {
                xBackend.UpdateMessage m = (xBackend.UpdateMessage)message;
                OnUpdate(m.Position, m.Orientation);
            }
        }
    }
}
